package com.leetcode.algorithms.one.problem7;

import org.junit.Test;

/**
 * Example 1:
 *
 * Input: 123
 * Output: 321
 * Example 2:
 *
 * Input: -123
 * Output: -321
 * Example 3:
 *
 * Input: 120
 * Output: 21
 */
public class ReverseInteger {
    @Test
    public void run(){
        int x = -2147483412;
        System.out.println(reverse(x));
    }

    public int reverse(int x) {
        //先求位数

        long xx = Math.abs((long)x);
        int i=0;
        long k=1;
        for(;i<11;i++){
            if(xx/k>0){
                k=k*10;
            }else {
                break;
            }
        }
        //位数就是i
        long result =0;
//        int m=10;
        for(int j=0;j<i;j++){
//            xx
            long pow = (long) Math.pow(10, i - 1-j);
            long y=xx/pow;
            long z= (long) Math.pow(10,j);
            result+= y*z;
            xx= (int) (xx%pow);

        }
        if(result>Integer.MAX_VALUE)
            return 0;
        if(x<0)
            result=0-result;

        return (int) result;
    }
}
